# -*- coding: utf-8 -*-
# @Project : meiduo_ninja
# @File : testrequest.py
# @IDE : PyCharm
# @Author : 吴灿星
# @Date : 2025/3/8 15:18
# @V: ValarMorghulis520

from ninja import NinjaAPI, Schema

# 定义一个简单的 API
from ninja_extra import service_resolver, NinjaExtraAPI
from ninja_extra.controllers import RouteContext
from pydantic import ValidationError

api = NinjaExtraAPI(urls_namespace='test')


# 定义一个 Schema，包含一个动态解析的字段
class Data(Schema):
    a: int
    path: str = ""

    def b(self):
        """此种获取上下文方式只能在NinjaExtraAPI中使用"""
        context: RouteContext = service_resolver(RouteContext)
        print(context)
        pass
    # 动态解析 path 字段
    @staticmethod
    def resolve_path(obj, context):
        """此种获取上下文方式在NinjaExtraAPI和NinjaAPI中都能使用"""
        # print('obj',obj)
        # print('con',context)
        request = context["request"]
        return request.path


# 视图函数
@api.get("/example")
def example(request):
    # 创建 Schema 实例，并传递上下文
    try:
        data = Data.model_validate({"a": 123}, context={"request": request})
        data.b()

        return data.dict()
    except ValidationError as exc:
        return {"error": exc.errors()}
